package com.hyl.authdemo.service;

import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.hyl.authdemo.config.SMSConfig;
import com.hyl.authdemo.util.CodeUtil;
import com.hyl.authdemo.util.CommenCode;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Set;

/**
 * @Description TODO
 * @Author hyl
 * @Date 2022/7/6 15:35
 **/
@Service("phoneService")
public class PhoneServiceImpl implements PhoneService {

	@Resource
	private SMSConfig smsConfig;

	@Resource
	private RedisService redisService;

	@Override
	public void send(String phone) {
		String code = CodeUtil.getCode(4); //验证码
		Integer time = 5;//有效时间
		//发送短信
		boolean isSuccess = sendrl(phone, code, time.toString());
		if (isSuccess){
			//存入缓存中
			redisService.set(CommenCode.USER_LOGIN_SMS_+phone, code, time);
		}
	}

	//容联云：发短信
	private boolean sendrl(String phone,String code,String time){
		//创建短信对象
		CCPRestSmsSDK sdk = new CCPRestSmsSDK();
		sdk.init(smsConfig.getServerIP(), smsConfig.getServerPort(),true);
		sdk.setAccount(smsConfig.getAccountSid(), smsConfig.getAuthToken());
		sdk.setAppId(smsConfig.getAppID());
		sdk.setBodyType(BodyType.Type_XML);

		//发送短信信息
		String to = phone;//"18670586910";
		String templateId= "1";
		String[] datas = {code,time};
		String subAppend="1234";  //可选	扩展码，四位数字 0~9999
		String reqId="***";  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
		HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);
		if("000000".equals(result.get("statusCode"))){
			//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}
			return true;
		}else{
			//异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
		}
		return false;
	}
}
